#include "../include/EchoServer.hpp"
#include "../include/Mylogger.hpp"
#include <iostream>
using std::cout;
using std::endl;


namespace cdm{

EchoServer::EchoServer(uint16_t port,const string ip,int thd,int taskSize)
:_server(port,ip),
_thdpool(thd,taskSize){
    using namespace std::placeholders;
    _server.setAllCallback(std::bind(&EchoServer::onConnected,this,_1),
                           std::bind(&EchoServer::onMessage,this,_1),
                           std::bind(&EchoServer::onClose,this,_1));
}

void EchoServer::start(){
    _thdpool.start();
    _server.start();
}

void EchoServer::stop(){
    _thdpool.stop();
    _server.unLoop();
}

void EchoServer::onConnected(TCPConnectionPtr conn){
    LOG_INFO(conn->toString()+" has connected successfully.");
}

void EchoServer::onMessage(TCPConnectionPtr conn){
    
    Packet packet;
    int ret = conn->readPacket(packet);
    cout<<"read bytes:"<<ret<<endl
        <<"read type:"<<packet._type<<endl
        <<"read length:"<<packet._length<<endl
        <<"read msg:"<<packet._msg<<endl;
    switch(packet._type){
    case TASK_LOGIN1:
        {
            UserLoginSection1 uls1(conn,packet);
            _thdpool.addTask(std::bind(&UserLoginSection1::process,uls1));
            break;
        }

    case TASK_LOGIN2:
        {
           UserLoginSection2 uls2(conn,packet);
           _thdpool.addTask(std::bind(&UserLoginSection2::process,uls2));
           break;
        }

    case TASK_REGISTER1:
        {
            
            break;
        }

    case TASK_REGISTER2:
        {
            
            break;
        }
    default:
        {
            string msg = conn->recive(); 
            Mytask task(packet._msg, conn);
            _thdpool.addTask(std::bind(&Mytask::process, task));
            string response = packet._msg;
            conn->send(response);
            break;
        }
    }

    /* Mytask task(msg, conn); */
    /* _thdpool.addTask(std::bind(&Mytask::process, task)); */
    /* string response = msg; */
    /* conn->send(response); */

}

void EchoServer::onClose(TCPConnectionPtr conn){
    LOG_INFO(conn->toString()+" has closed.");
}


}//end of cdm

